<template>
  <div class="app-container">
    <div class="search-container">
      <el-form v-show="showSearch" ref="queryParamsRef" :inline="true" :model="queryParams" label-width="100px">
        <el-form-item label="计费时间段" prop="">
          <el-date-picker v-model="dateRange" :shortcuts="$shortcuts()" :unlink-panels="true"
                          end-placeholder="结束日期" range-separator="截止"
                          start-placeholder="开始日期" type="datetimerange" value-format="YYYY-MM-DD HH:mm:ss"
                          @change="handleQuery"></el-date-picker>
        </el-form-item>
        <el-form-item v-if="isReturnOk" label="患者姓名" prop="name">
          <el-input
            v-model="queryParams.name"
            clearable
            placeholder="请输入患者姓名"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="药品名称" prop="itemName">
          <el-input
            v-model="queryParams.itemName"
            clearable
            placeholder="请输入药品名称"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <query-form-button @handleQuery="handleQuery" @resetQuery="resetQuery"/>
        </el-form-item>
        <div v-if="!isReturnOk"
             style="margin-top: -10px;padding-bottom: 5px;margin-left: 20px;color: #ff0303;font-size: 12px">
          【退药数量】不填写或者填写0，表示【不退药】，如果有需要退药的药品，请修改【退药数量】，点击右下角【确定】按钮提交即可。
        </div>
      </el-form>
    </div>
    <el-row :gutter="10" class="mb8">
      <!--            <el-col :span="1.5">-->
      <!--                <el-button-->
      <!--                    type="primary"-->
      <!--                    plain-->
      <!--                    @click="handleAdd"-->
      <!--                    v-hasPerm="['business:inpBillDetail:add']"-->
      <!--                >-->
      <!--                    <template-->
      <!--                        #icon>-->
      <!--                        <i-ep-plus/>-->
      <!--                    </template>-->
      <!--                    新增-->
      <!--                </el-button>-->
      <!--            </el-col>-->
    </el-row>
    <el-form ref="formRef" :model="form">
      <el-table v-adaptive="tableHeight" :border="true" :data="form.returnDrugList"
                :header-cell-style="$headerCellStyle" :stripe="true"
                :summary-method="getSummaries" default-expand-all highlight-current-row show-summary>
        <el-table-column fixed="left" label="明细" type="expand">
          <template #default="props">
            <div m="4">
              <el-table :border="true" :data="props.row.repercussionApplyVoList" :stripe="true"
                        highlight-current-row>
                <el-table-column fixed="left" width="50px"/>
                <el-table-column :align="'center'" :show-overflow-tooltip="true" fixed="left"
                                 label="药品名称"
                                 prop="drugName"
                                 width="130">
                  <template #default="scope">
                    <span class="ys-css">{{ scope.row.drugName }}</span>
                  </template>
                </el-table-column>
                <el-table-column :align="'center'" label="项目规格" prop="itemSpec" width="140"/>
                <el-table-column :align="'center'" label="退药状态"
                                 prop="returnDrugStatusName"
                                 width="100">
                  <template #default="scope">
                    <dict-data-tag :options="dictDataMap['return_drug_status']"
                                   :value="scope.row.returnDrugStatus"/>
                  </template>
                </el-table-column>
                <el-table-column :align="'center'" label="总数量"
                                 prop="dispensingAmountShow"
                                 width="120">
                  <template #default="scope">
                                        <span
                                          class="ys-css">{{
                                            parseFloat(scope.row.dispensingAmountShow.toString()).toFixed(0)
                                          }}</span>{{ scope.row.unitsName }}
                  </template>
                </el-table-column>
                <el-table-column :align="'center'"
                                 label="已申请退药数量"
                                 prop="returnAmountShow" width="140">
                  <template #default="scope">
                                        <span
                                          class="ret-ys-css">{{
                                            parseFloat(scope.row.returnAmountShow.toString()).toFixed(0)
                                          }}</span>{{ scope.row.unitsName }}
                  </template>
                </el-table-column>
                <el-table-column :align="'center'" label="退药剩余数量"
                                 prop="remainingAmountShow"
                                 width="120">
                  <template #default="scope">
                                        <span
                                          class="ys-css">{{
                                            parseFloat((scope.row.remainingAmountShow).toString()).toFixed(0)
                                          }}</span>{{ scope.row.unitsName }}
                  </template>
                </el-table-column>
                <el-table-column :align="'center'" :show-overflow-tooltip="true"
                                 class-name="small-padding fixed-width" fixed="right"
                                 label="操作" width="80">
                  <template #default="scope">
                    <el-tooltip class="item" content="撤销" effect="dark" placement="top">
                      <el-button
                        v-if=" !isReturnOk && (scope.row.returnDrugStatus === '1' || scope.row.returnDrugStatus === '2')"
                        circle type="danger"
                        @click="revokeItem(scope.row)">
                        <template #icon>
                          <svg-icon icon-class="cheXiao"/>
                        </template>
                      </el-button>
                    </el-tooltip>

                    <el-tooltip class="item" content="确认退药" effect="dark" placement="top">
                      <el-button
                        v-if=" isReturnOk && scope.row.returnDrugStatus === '2'"
                        circle type="success"
                        @click="confirmDrugRepercussionFun(scope.row)">
                        <template #icon>
                          <svg-icon icon-class="start"/>
                        </template>
                      </el-button>
                    </el-tooltip>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </template>
        </el-table-column>
        <el-table-column :align="'center'" fixed="left" header-align="center" label="序号" prop="itemPrice"
                         width="50">
          <template #default="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column :align="'center'" fixed="left" label="费用发生时间" prop="medicalVerifyTime"
                         width="170">
          <template #default="scope">
            <span class="ys-css">{{ $parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column :align="'center'" fixed="left" label="患者信息" prop="medicalVerifyTime"
                         width="170">
          <template #default="scope">
            <span class="ys-css">{{ scope.row.name }}</span>
            <span style="margin-left: -10px">
                            <svg-icon :icon-class="dictStore.getMateDictInfo(
                                dictDataMap['sys_user_sex'],
                                scope.row.sex
                            ).dictValue === '1'
                                ? 'man'
                                : 'woman'
                                " style="margin-left: 10px"/>
                        </span>
            {{ scope.row.ageAll }}
          </template>
        </el-table-column>
        <el-table-column :align="'center'" fixed="left" label="开单科室" prop="applyDeptName" width="100"/>
        <el-table-column :align="'center'" fixed="left" label="开单医生" prop="applyDoctorName" width="100"/>
        <el-table-column :align="'center'" fixed="left" label="执行科室" prop="implementDeptName" width="90"/>
        <el-table-column :align="'center'" fixed="left" label="患者所在科室" prop="deptStayedName" width="100"/>
        <el-table-column :align="'center'" fixed="left" label="患者所在病区" prop="wardCodeName" width="100"/>
        <el-table-column :align="'center'" :show-overflow-tooltip="true" fixed="left" label="药品名称"
                         prop="itemName">
          <template #default="scope">
            <span class="ys-css">{{ scope.row.itemName }}</span>
          </template>
        </el-table-column>
        <el-table-column :align="'center'" fixed="left" label="项目规格" prop="itemSpec" width="140"/>
        <el-table-column :align="'right'" header-align="center" label="单价(元)" prop="itemPrice" width="100">
          <template #default="scope">
            <span class="ys-css">{{ parseFloat(scope.row.itemPrice.toString()).toFixed(2) }}</span>元
          </template>
        </el-table-column>
        <el-table-column :align="'right'" header-align="center" label="实收费用(元)" prop="charges" width="100">
          <template #default="scope">
            <span class="ys-css">{{ parseFloat(scope.row.charges.toString()).toFixed(2) }}</span>元
          </template>
        </el-table-column>
        <el-table-column :align="'left'" fixed="left" header-align="center" label="总数量" prop="amount"
                         width="120">
          <template #default="scope">
                    <span
                      class="ys-css">{{
                        parseFloat(scope.row.amount.toString()).toFixed(0)
                      }}</span>{{ scope.row.unitsName }}
          </template>
        </el-table-column>
        <el-table-column v-if="!isReturnOk" :align="'left'" fixed="left" header-align="center" label="退药数量"
                         prop="returnAmountInput"
                         width="135">
          <template #default="scope">
            <el-input v-if="!isReturnOk" v-model="scope.row.returnAmountInput"
                      :disabled="scope.row.remainingAmountShow === 0" class="groupNumber" clearable
                      prop="groupNumber" @blur="returnAmountInputBlur(scope.$index, scope.row)">
              <template #append>{{ scope.row.unitsName }}</template>
            </el-input>
            <span v-else>{{ scope.row.returnAmountInput }}&nbsp;{{ scope.row.unitsName }}</span>
          </template>
        </el-table-column>
        <el-table-column :align="'left'" fixed="left" header-align="center" label="已申请退药数量"
                         prop="returnAmountShow" width="80">
          <template #default="scope">
                    <span
                      class="ret-ys-css">{{
                        parseFloat(scope.row.returnAmountShow.toString()).toFixed(0)
                      }}</span>{{ scope.row.unitsName }}
          </template>
        </el-table-column>
        <el-table-column :align="'left'" fixed="left" header-align="center" label="退药剩余数量"
                         prop="remainingAmountShow"
                         width="90">
          <template #default="scope">
                    <span
                      class="ys-css">{{
                        parseFloat((scope.row.remainingAmountShow).toString()).toFixed(0)
                      }}</span>{{ scope.row.unitsName }}
          </template>
        </el-table-column>
      </el-table>
    </el-form>
  </div>
</template>
<script lang="ts" setup>
import {useUserStoreHook} from "@/store/modules/user.ts";
import {useDictStoreHook} from "@/store/modules/dict.ts";
import {listDrugRepercussion} from "@/api/hospitalization/inpBillDetail.ts";
import {
  addDrugRepercussionApply,
  confirmDrugRepercussion,
  updateDrugRepercussionApply
} from "@/api/drug/DrugRepercussionApply.ts"


const useUserStore = useUserStoreHook();
const dictStore = useDictStoreHook();
let dictDataMap = ref(dictStore.isTypeGetData('return_drug_status', 'sys_user_sex'))

const {proxy} = getCurrentInstance() as any;
// 登录用户信息
const userInfo = <UserInfoBusi>useUserStore.user.userInfo;
const queryParamsRef = ref()
const showSearch = ref(true);
// 退药申请表格高度
const tableHeight = ref(330)
const date = proxy.$parseTime(new Date(), "{y}-{m}-{d} ");
const dateRange = ref([date + "00:00:00", date + "23:59:59"]);
const emits = defineEmits(["submitForm"])
const props = defineProps({
  isReturnOk: {
    type: Boolean,
    default: true
  }
})
const queryParams = ref({
  patientId: "",
  visitId: "",
  orgId: userInfo.orgId,
  name: "",
  itemName: '',
  isReturnOk: props.isReturnOk
})

const form = ref<any>({
  // 退药数量list
  returnDrugList: []
})


if (!props.isReturnOk) {
  tableHeight.value = 330
} else {
  tableHeight.value = 30
}

/**
 * 父组件加载初始化方法
 */
function initOpen(obj: any) {
  queryParams.value.visitId = obj.visitId;
  queryParams.value.patientId = obj.patientId;
  getList()
}

/** 查询住院费用inp_bill_detail列表 */
function getList() {
  queryParams.value.isReturnOk = props.isReturnOk
  listDrugRepercussion(proxy.$addDateRange(queryParams.value, dateRange.value)).then((response: any) => {
    form.value.returnDrugList = []
    form.value.returnDrugList = response.data;
    form.value.returnDrugList.forEach((item: any) => {
      // 主记录 退药后剩余数量显示   如果是医嘱开的是大包装，除以包装数量
      // remainingAmount  退药后剩余数量 默认为小包装
      item.remainingAmountShow = item.packSize === '2' ? item.remainingAmount / item.packageNum : item.remainingAmount
      // 主记录 退药数量显示 如果是医嘱开的是大包装，除以包装数量
      // returnAmount 退药数量 默认为小包装
      item.returnAmountShow = item.packSize === '2' ? item.returnAmount / item.packageNum : item.returnAmount
      // 主记录 退药后剩余数量显示   开药数量- 退药数量
      item.remainingAmountShow = item.amount - item.returnAmountShow
      item.returnAmountInput = 0
      if (item.repercussionApplyVoList) {
        item.repercussionApplyVoList.forEach((itemRepercussionApply: any) => {
          // 明细 退药后剩余数量显示   如果是医嘱开的是大包装，除以包装数量
          // 明细 remainingAmount  退药后剩余数量 默认为小包装
          itemRepercussionApply.remainingAmountShow = itemRepercussionApply.packSize === '2' ?
            itemRepercussionApply.remainingAmount / itemRepercussionApply.packageNum : itemRepercussionApply.remainingAmount

          // 明细 退药数量显示 如果是医嘱开的是大包装，除以包装数量
          // 明细 returnAmount 退药数量 默认为小包装
          itemRepercussionApply.returnAmountShow = itemRepercussionApply.packSize === '2' ?
            itemRepercussionApply.returnAmount / itemRepercussionApply.packageNum : itemRepercussionApply.returnAmount

          // 明细 开药总数量显示 如果是医嘱开的是大包装，除以包装数量
          // 明细 dispensing 退药数量 默认为小包装
          itemRepercussionApply.dispensingAmountShow = itemRepercussionApply.packSize === '2' ?
            itemRepercussionApply.dispensingAmount / itemRepercussionApply.packageNum : itemRepercussionApply.dispensingAmount

          // 明细 退药后剩余数量显示   开药数量- 退药数量
          itemRepercussionApply.remainingAmountShow = itemRepercussionApply.dispensingAmountShow - itemRepercussionApply.returnAmountShow
          itemRepercussionApply.unitsName = item.unitsName
          itemRepercussionApply.itemSpec = item.itemSpec
        })
      }
    })
  });
}

/** 搜索按钮操作 */
function handleQuery() {
  getList();
}

/** 清空 */
function empty() {
  queryParamsRef.value.resetFields()
  dateRange.value = [date + "00:00:00", date + "23:59:59"]
  form.value.returnDrugList = []
}

/** 重置按钮操作 */
function resetQuery() {
  queryParamsRef.value.resetFields()
  dateRange.value = [date + "00:00:00", date + "23:59:59"]
  handleQuery();
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('business/inpBillDetail/export', {
    ...queryParams.value
  }, `inpBillDetail_${new Date().getTime()}.xlsx`)
}

/* 退药数量输入框焦点消失事件*/
function returnAmountInputBlur(index: number, row) {
  const indexS: number = Number(index) + 1
  if (row.returnAmountInput > row.remainingAmountShow) {
    return ElMessage.error("第" + indexS + "行，药品：【" + row.itemName + "】,申请退费数量大于开单数量，请重新填写【退药数量】")
  }
}

/**
 * 退药申请提交
 */
function submitForm() {
  let drugRepercussionApplyBoList: any = []
  for (let index = 0; index < form.value.returnDrugList.length; index++) {
    const item = form.value.returnDrugList[index]
    const indexS: number = Number(index) + 1
    if (item.returnAmountInput !== undefined && item.returnAmountInput > item.remainingAmountShow) {
      return ElMessage.error("第" + indexS + "行，药品：【" + item.itemName + "】,申请退费数量大于开单数量，请重新填写【退药数量】")
    }
    let drugDispensingItemRecordBo = {
      dispensingItemRecordId: item.dispensingItemRecordId,
      prescriptionItemId: item.prescriptionItemId,
      inpBillDetailId: item.inpBillDetailId,
      identicalInfoId: item.identicalInfoId,
      returnAmount: item.returnAmountInput,
      dispensingAmount: Number(item.amount).toFixed(0),
      visitId: item.visitId,
      patientId: item.patientId,
      orgId: item.orgId,
      packageNum: item.packageNum,
      packSize: item.packSize,
      drugName: item.itemName,
      storageId: item.storageId,
    }
    drugRepercussionApplyBoList.push(drugDispensingItemRecordBo)
  }
  let returnDrugList = drugRepercussionApplyBoList.filter((item: any) => item.returnAmount != 0 && item.returnAmount != null)
  if (returnDrugList.length <= 0) {
    return ElMessage.error("没有需要申请退药的药品，不能提交。")
  }
  ElMessageBox.confirm('确定要提交退药申请吗？',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    const form = {
      drugRepercussionApplyBoList: returnDrugList,
      orgId: userInfo.orgId,
      visitId: queryParams.value.visitId,
      patientId: queryParams.value.patientId
    }
    addDrugRepercussionApply(form).then(() => {
      ElMessage.success("提交成功");
      getList()
    })
  }).catch(() => {
  })
}

const getSummaries = (param: any) => {
  const {columns, data} = param
  const sums: (string | VNode)[] = []
  columns.forEach((column, index) => {
    if (index === 8) {
      // sums[index] = h('div', { style: { textDecoration: 'underline' } }, [
      sums[index] = h('div', {style: {'float': 'right', 'color': 'rgb(51, 91, 249)', 'font-size': '15px'}}, [
        '合计：',
      ])
      return
    }
    if (index === 9) {
      const values = data.map((item) => Number(item[column.property]))
      if (!values.every((value) => Number.isNaN(value))) {
        sums[index] = `￥ ${values.reduce((prev, curr) => {
          const value = Number(curr)
          if (!Number.isNaN(value)) {
            return (Number(prev) + Number(curr)).toFixed(2)
          } else {
            return (Number(prev)).toFixed(2)
          }
        }, 0)} 元`
      } else {
        sums[index] = ''
      }
    }
  })

  return sums
}

/**
 * 退药申请撤销
 */
function revokeItem(row: any) {
  ElMessageBox.confirm('确定要【撤销】吗？',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    const param = {
      drugRepercussionApplyId: row.drugRepercussionApplyId,
      returnDrugStatus: "1"
    }
    updateDrugRepercussionApply(param).then(() => {
      ElMessage.success("操作成功")
      getList()
    })
  }).catch(() => {
  })
}

/**
 * 确认退药
 * @param row
 */
function confirmDrugRepercussionFun(row: any) {
  ElMessageBox.confirm('确定要【确认退药】吗？',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    const param = {
      drugRepercussionApplyId: row.drugRepercussionApplyId,
      returnDrugStatus: "4",
      inoroutFlag: row.inoroutFlag,
      inpBillDetailId: row.inpBillDetailId,
      packageNum: row.packageNum,
      packSize: row.packSize,
    }
    confirmDrugRepercussion(param).then(() => {
      ElMessage.success("确认退药成功、药品库存以回退")
      getList()
    })
  }).catch(() => {
  })
}


defineExpose({
  initOpen,
  submitForm,
  empty
})
getList()
</script>

<script lang="ts">
export default {
  name: "DrugRepercussion"
}
</script>


<style scoped>
:deep(.el-drawer__header) {
  margin-bottom: 0;
}
</style>
